package com.expires.test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @program: SpringBootDemos
 * @description: 栅栏 拦住一组线程 等待到某个状态后 放行 一组线程一起执行
 * @author: Kangsen
 * @create: 2022-06-09 10:13
 **/

public class CyclicBarrierTestCase {

    static class Worker implements Runnable{
        private CyclicBarrier cyclicBarrier;
        private int time;
        public Worker(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            System.out.println("线程"+Thread.currentThread().getName() +" 准备执行任务呀");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            while(true){
                if(status == 1){
                    System.out.println("线程"+Thread.currentThread().getName() +" 执行任务");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException  e) {
                        e.printStackTrace();
                    }
                    System.out.println("线程"+Thread.currentThread().getName() +" 执行任务完毕");
                    break;
                }
            }
        }
    }

    static int num = 5;
    static volatile int status = 0;
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(num, new Runnable() {
            @Override
            public void run() {
                System.out.println("集结队伍完毕 2s后执行任务");
                try {
                    TimeUnit.SECONDS.sleep(2);
                    status = 1;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("集结队伍 准备执行任务");
        for (int i = 0; i < num; i++) {
            new Thread(new Worker(cyclicBarrier)).start();
        }
    }

}
